package com.wiz.weixin.util;

import java.security.MessageDigest;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

public class MiscUtil {

	/**
	 * 获取IP地址
	 * 
	 * @param request
	 * @return IP地址String
	 */
	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		if (ip != null && ip.indexOf(",") != -1) {
			String[] array = ip.split(",");
			for (String str : array) {
				if (str.indexOf("127.0.0.1") < 0 && str.indexOf("192.168.") < 0) {
					return str.trim();
				}
			}
		}
		return ip;
	}
	
	public static String getRandomId(){
		StringBuffer sb = new StringBuffer();
		Random rand = new Random();
		int i = rand.nextInt(999999)+100000;
		sb.append(String.valueOf(System.currentTimeMillis()));
		sb.append(i);
		return sb.toString();
	}
	
	public static String getRandomCode(){
        Random rand = new Random();
        return String.valueOf(rand.nextInt(999999)+100000);
    }

	/**
	 * 验证md5加密
	 * @param str 未加密字符串
	 * @param encodeStr 已加密字符串
	 * @return
	 */
	public static boolean checkEncodeMd5String(String str, String encodeStr) {
		return encodeByMd5(str).equals(encodeStr);
	}
	
	 /**
     * 对字符串进行MD5编码
     *
     * @param originstr 需要加密字符串
     * @return 加密结果
     */
    public static String encodeByMd5(String originstr) {
        if (originstr != null) {
            try {
                //创建具有指定算法名称的信息摘要
                MessageDigest md = MessageDigest.getInstance("MD5");
                //使用指定的字节数组对摘要进行最后的更新，然后完成摘要计算
                byte[] results = md.digest(originstr.getBytes());
                //将得到的字节数组编程字符窜返回
                return byte2Hex(results);
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }
        return null;
    }
    
    /**
     * @param paramArrayOfByte 字符数组
     * @return 十六进制转换结果
     */
    private static String byte2Hex(byte[] paramArrayOfByte) {
        StringBuilder stringBuilder = new StringBuilder();
        String str;
        for (byte aParamArrayOfByte : paramArrayOfByte) {
            str = Integer.toHexString(aParamArrayOfByte & 0xFF);
            if (str.length() == 1)
                stringBuilder.append("0");
            stringBuilder.append(str);
        }
        return stringBuilder.toString();
    }

	public static boolean verifyCheckResult(String checkResult) {
		return checkResult.startsWith("{\"code\":200");
    }
	
	public static void main(String[] args) {
	    System.out.println(MiscUtil.encodeByMd5("111111"));
	}
}